<!-- 联系人编辑页 -->
<template>
	<view style="background-color: #fff;padding:10px 10px 50px 10px">
		<!-- 自定义头部组件 -->
		<HeaderTitle :title="title" :isBack="true" :isSearch="false" />
		<!-- 备案表单内容区域 -->
		<div class="container">
			<uni-forms ref="form" :modelValue="entity" label-width="100px" :rules="dynamicRules">
				<div class="client" style="padding-bottom:67px;">
					<uni-forms-item label="客户名称：" :rules="$rules.handle.CustomerName" required name="CustomerName">
						<div @click="CustomerChoice">
							<uni-easyinput v-model="entity.CustomerName" placeholder="请选择客户" suffixIcon="search"
								:disabled="true" />
						</div>
					</uni-forms-item>
					<uni-forms-item label="姓名：" :rules="$rules.handle.Name" required name="Name">
						<uni-easyinput v-model="entity.Name" placeholder="请输入姓名" :disabled="disabled" />
					</uni-forms-item>
					<uni-forms-item label="职位:" v-model="entity.Position" placeholder="请输入职位">
						<uni-easyinput v-model="entity.Position" placeholder="请输入职位" :disabled="disabled" />
					</uni-forms-item>
					<uni-forms-item label="组织机构:" v-model="entity.Department" placeholder="请输入组织机构">
						<uni-easyinput v-model="entity.Department" placeholder="请输入组织机构" :disabled="disabled" />
					</uni-forms-item>
					<div>
						<div label="" v-if="WordList.length>0" style="display:flex;flex-wrap: wrap;padding-left: 20px;">
							<u-tag type="primary" v-for="(item, index) in WordList" :key="index" closeable
								class="tagClass" :closeable="!disabled" @close="closeTag(index)" :text="item"></u-tag>
						</div>

						<uni-forms-item v-if="!disabled" label="角色名称:" :rules="$rules.handle.RoleName" required
							name="RoleName">
							<!-- @click="downRoleClick"  -->
							<uni-data-select v-model="entity.RoleName" :localdata="columnsRoleData"
								placeholder="请输入角色名称(请使用【回车】分词)" @change="columnsRoleConfirm"
								:disabled="disabled"></uni-data-select>
						</uni-forms-item>
					</div>
					<uni-forms-item label="电话:" :rules="$rules.handle.Tel_Code" required name="Tel_Code">
						<uni-easyinput v-model="entity.Tel_Code" placeholder="请输入电话" type="number" @input="inputChange"
							:disabled="disabled" />
					</uni-forms-item>
					<uni-forms-item label="电子邮箱:">
						<uni-easyinput v-model="entity.Email" placeholder="请输入电子邮箱" :disabled="disabled" />
					</uni-forms-item>
					<uni-forms-item name="cProvinceName" label="省:">
						<uni-data-select placeholder="请选择省份" v-model="entity.cProvinceName"
							@change="cProvinceNameChange" :localdata="columnscProvince"
							:disabled="disabled"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item name="cCityName" label="市:">
						<uni-data-select placeholder="请选择市" v-model="entity.cCityName" :localdata="columnscCity"
							@change="cCityNameChange" :disabled="disabled"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item name="cCountyName" label="区:">
						<uni-data-select placeholder="请选择区" v-model="entity.cCountyName" :localdata="columnscCounty"
							@change="cCountyNameChange" :disabled="disabled"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="详细地址:">
						<view @click="addressClick">
							<uni-easyinput v-model="entity.Address" placeholder="请输入详细地址" :disabled="disabled" />
						</view>

					</uni-forms-item>
					<uni-forms-item label="备注:">
						<uni-easyinput v-model="entity.Remark" placeholder="请输入备注" type="textarea"
							:disabled="disabled" />
					</uni-forms-item>
					<uni-forms-item label="上传名片">
						<UploadImg ref="UploadImg" @onSuccess="onSuccess" :file="uploadFile"
							@handlerRemove="handlerRemove" :deletable="disabled">
						</UploadImg>
					</uni-forms-item>
				</div>
				<div v-if="!disabled">
					<div class="submitButton">
						<u-button type="primary" style="font-size: 14px;margin-top: 20rpx;" @click="onSubmit"
							:loading="loading">提交</u-button>
					</div>
				</div>
			</uni-forms>
			<!-- 客户组件 -->
			<Myuser @customerChoice="Client" ref="myuser" />
			<!-- 地址组件 -->
			<Address @addressClickChange="AddressChangeChoice" ref="Address" />
		</div>
	</view>

</template>
<script>
	import {
		GetDataListByPIdListProvince,
		GetDataListByPIdListcCity,
		GetDataListByPIdListcCounty,
		CustomerInfoSaveData,
		Cust_CustomerApplySaveData,
		GetTheDataByDicKey,
		Cust_CustomerLinkManUpdateData,
		Cust_CustomerLinkManGetTheData
	} from '@/api/interface.js'
	// 地址组件
	import Address from "../../components/address.vue";
	// 客户租金啊
	import Myuser from "../../components/OwnUser.vue";
	// 上传名片组件
	import UploadImg from "../../components/UploadImg.vue"
	// 引入顶部navbar组件
	import HeaderTitle from '@/components/header/header-title.vue'
	export default {
		components: {
			Address,
			UploadImg,
			Myuser,
			HeaderTitle
		},
		data() {
			return {
				// 客户id
				CustomerId: "",
				loading: false,
				// 上传的附件
				uploadFile: [],
				// 电子邮箱格式校验
				dynamicRules: {
					Email: {
						rules: [{
								required: false,
								message: "",
							},
							{
								validateFunction: (rule, value, data, callback) => {
									let iphoneReg = (
										/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
									); //手机号码
									if (!iphoneReg.test(value)) {
										callback('邮箱格式不正确，请重新填写')
									}
								}
							}
						],
					}
				},
				// 按钮是否禁用
				disabled: false,
				// 导航栏标题  0新增 1修改
				title: "",
				// 上传后返回的图片路径
				thumbUrl: "",
				obj: null,
				ListProvince: [],
				isShowRoleData: false,
				// 角色本来数据
				columnsRoleData: [{
						value: 0,
						text: "主管"
					},
					{
						value: 1,
						text: "经理"
					},
					{
						value: 2,
						text: "技术"
					},
					{
						value: 3,
						text: "决策人"
					},
					{
						value: 4,
						text: "老板"
					},
					{
						value: 5,
						text: "采购负责人"
					},
					{
						value: 6,
						text: "采购员"
					},
					{
						value: 7,
						text: "技术主管"
					},
					{
						value: 8,
						text: "总经理"
					}
				],
				// 角色名称标签数据
				WordList: [],
				// 上传附件列表数据
				fileList: [
					// { url: "https://img01.yzcdn.cn/vant/leaf.jpg" },
					// Uploader 根据文件后缀来判断是否为图片文件
					// 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
					// { url: "https://cloud-image", isImage: true }
				],
				// fileList: [
				//   { url: "https://img01.yzcdn.cn/vant/leaf.jpg" },
				//   // Uploader 根据文件后缀来判断是否为图片文件
				//   // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
				//   { url: "https://cloud-image", isImage: true }
				// ],
				columnscProvince: [], //省
				columnscCity: [], //市
				columnscCounty: [], //区
				listChildren: [],
				listcounty: [],
				entity: {
					CustomerName: "",
					reportPic: ""
				},
				// 1是编辑  0是新建
				options: {},
				title: ""

			};
		},
		onLoad(options) {
			this.options = options
			this.title = options.title
			// uni.setNavigationBarTitle({
			// 	title: options.title
			// })
			console.log('开始编辑了', options)
			if (options.title === '查看联系人') {
				this.disabled = true
				this.$nextTick(function() {
					this.$refs.UploadImg.show = true
					this.$refs.UploadImg.deletable = false
				})
			} else {
				this.disabled = false
				this.$nextTick(function() {
					this.$refs.UploadImg.show = false
					this.$refs.UploadImg.deletable = true
				})
			}
			if (options.Id) {
				this.getCust_CustomerLinkManGetTheData()
			}

		},

		methods: {
			// 只能输入正整数
			inputChange(event) {
				const inputRule = /[^1-9]/g //只能输入正整数
				if (event < 0) {
					this.$nextTick(() => {
						this.$set(this.entity, 'Tel_Code', inputRule);
					});
				}
			},
			// 上传附件成功
			onSuccess(file) {
				this.fileList = file
				let BusinessCardURLArr = this.fileList.map(item => {
					return item.url
				})
				let BusinessCardURL = BusinessCardURLArr.join(',')
				this.entity.BusinessCardURL = BusinessCardURL
				console.log('上传传过来了', file, this.fileList, this.uploadFile, this.entity, BusinessCardURL)
			},
			// 移除附件
			handlerRemove(list, index) {
				this.uploadFile.splice(index, 1)
				let uploadFileArr = this.uploadFile.map(item => {
					return item.url
				})
				this.entity.BusinessCardURL = uploadFileArr.join(',')
			},

			// 选择省份变化事件
			cProvinceNameChange(event) {
				this.entity.cCountyName = -1
				this.$forceUpdate()
				let ProvinceId = this.ListProvince[event].Id
				this.entity.Province = ProvinceId
				// 获取市信息
				this.getCityListData(ProvinceId, '改变')
			},
			// 市级变化回调
			cCityNameChange(event) {
				this.$forceUpdate()
				let ProvinceId = this.listChildren[event].Id
				this.entity.City = ProvinceId
				// 获取区信息
				this.getVillage(ProvinceId, '改变')
			},
			// 区改变事件
			cCountyNameChange(event) {
				this.$forceUpdate()
				console.log('区改变', event, this.listcounty, this.entity)
				let ProvinceId = this.listcounty[event].Id
				this.entity.County = ProvinceId
			},



			// 获取联系人详情信息
			getCust_CustomerLinkManGetTheData() {
				Cust_CustomerLinkManGetTheData({
						Id: this.options.Id
					})
					.then(res => {
						if (res.Success) {

							this.entity = res.Data;

							// 处理角色回显
							if (this.entity.RoleName) {
								this.WordList = this.entity.RoleName.split(',')
							}
							// 处理附件上传回显
							if (this.entity.BusinessCardURL) {
								let arr = this.entity.BusinessCardURL.split(',')
								let newArr = []
								arr.forEach(item => {
									let obj = {
										url: item
									}
									newArr.push(obj)
								})
								this.$forceUpdate()
								this.uploadFile = newArr
							}
							this.getProvinceListData('详情')

						}
					})
					.catch(err => {
						this.$errorToast(err.Msg);
					});
			},

			// 详细地址点击事件
			addressClick() {

				if (this.disabled) return

				if (this.entity.CustomerName) {
					// 调取子组件里的方法
					this.$refs.Address.openForm(this.CustomerId)
					return
				} else {
					uni.showToast({
						title: '请先选择客户',
						icon: 'none'
					})
				}
			},

			// 地址组件传递过来的方法
			AddressChangeChoice(data) {
				this.$forceUpdate()
				// 将选中的数据赋值到form表单中
				this.entity.Address = data.Address;
				// 关闭地址弹窗
				this.isAddress = false;
			},

			//客户组件选择的本条客户的数据
			Client(a) {

				this.$set(this.entity, "CustomerName", a.cCusName);
				this.$set(this.entity, "CustomerId:", a.Id);
				this.CustomerId = a.Id
				this.$set(this.entity, "ParentId", a.Id);
				this.$set(this.entity, "cCusCode", a.cCusCode);
				console.log('客户选中了', this.CustomerId, this.entity);
			},

			// 客户组件传递过来的方法
			CustomerChoice(e) {
				if (this.disabled) return
				this.$refs.myuser.openForm();
			},

			// 关闭角色名称
			closeTag(index) {
				this.WordList.splice(index, 1);
				let arr = this.WordList.join(",");
				this.entity.RoleName = arr;
				console.log(index, this.entity);
			},
			// 角色数据点选
			columnsRoleConfirm(value) {
				let name = this.columnsRoleData[value].text
				if (this.WordList.length == 0) {
					this.WordList.push(name);
				} else {
					let isIncludes = this.WordList.indexOf(name);
					if (isIncludes != -1) {
						this.$errorToast("关键字不能重复或者为空");
						return
					}
					this.WordList.push(name);

				}
				if (this.WordList.length == 0) {
					this.entity.RoleName = ""
				} else if (this.WordList.length > 0 && this.WordList.length <= 1) {
					this.entity.RoleName = this.WordList[this.WordList.length]
				} else {
					this.entity.RoleName = this.WordList.join(',')
				}
			},
			// 表单提交
			onSubmit() {
				var that = this
				// 附件处理
				let fileList = this.fileList.map(item => {
					return item.url
				})
				let newUploadFile = fileList.join(',')
				console.log('newUploadFilenewUploadFile', newUploadFile)
				this.$refs.form.validate().then(res => {
					// 清空表单校验
					// this.resetFields()  
					this.loading = true
					uni.showLoading({
						title: '加载中'
					})

					// 编辑联系人
					Cust_CustomerLinkManUpdateData(this.entity)
						.then(resJson => {
							if (resJson.Success) {
								that.$sucessToast('修改成功')
								// if (this.urlType == 1) {
								//   // 从工单管理页面跳转过来的
								//   // 跳转回工单管理页面
								//   this.$router.push("/workOrder/workOrderManage");
								// } else {
								//   // 从我的工单页面跳转过来的
								//   // 跳转回我的工单页面
								//   this.$router.push("/workOrder/myWorkOrder");
								// }
								setTimeout(function() {
									that.loading = false
									uni.navigateBack()
									uni.hideLoading()
								}, 2500)
							} else {
								that.$errorToast(resJson.Msg);
								setTimeout(function() {
									that.loading = false
									uni.navigateBack()
									uni.hideLoading()
								}, 2500)
							}
						});

				}).catch(err => {
					uni.hideLoading()
					that.loading = false
				})
			},
			//获取省份信息
			getProvinceListData(type) {
				GetDataListByPIdListProvince({})
					.then(resJson => {
						this.ListProvince = resJson.Data;
						this.columnscProvince = resJson.Data.map((item, index) => {
							return {
								value: index,
								text: item.Name
							}
						});
						let index = resJson.Data.findIndex(item => item.Id === this.entity.Province)
						this.entity.cProvinceName = index
						if (type === '详情') {
							this.getCityListData(this.entity.Province, type)
						}

					});
			},
			// 获取市信息
			getCityListData(e, type) {
				GetDataListByPIdListcCity({
						Id: e
					})
					.then(resJson => {
						this.listChildren = resJson.Data;
						this.columnscCity = resJson.Data.map((item, index) => {
							return {
								value: index,
								text: item.Name
							}
						});

						let index = resJson.Data.findIndex(item => item.Id === this.entity.City)
						this.entity.cCityName = index
						if (type === '详情') {
							// 获取区级下拉列表数据
							this.getVillage(this.entity.City, type)
						}

					});
			},
			// 获取区信息
			getVillage(e, type) {
				GetDataListByPIdListcCounty({
						Id: e
					})
					.then(resJson => {
						this.listcounty = resJson.Data;
						this.columnscCounty = resJson.Data.map((item, index) => {
							return {
								value: index,
								text: item.Name
							}
						});

						let index = resJson.Data.findIndex(item => item.Id === this.entity.County)
						this.entity.cCountyName = index
					});
			},

		}
	};
</script>
<style lang="less" scoped>
	.container {}

	.tagClass {
		margin-right: 5px;
		margin-bottom: 5px;

		/* color: #000;
		padding: 5px;
		background-color: #ccc;
		border-radius: 8px;
		margin-left: 15px;
		margin-bottom: 5px; */
	}

	.submitButton {
		z-index: 999;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 65px;
		/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
		height: calc(58px + constant(safe-area-inset-bottom));
		/* 直接扩展高度，因为padding-bottom是内边距 */
		height: calc(78px + env(safe-area-inset-bottom));
		/* 直接扩展高度 */
		background: #fff;
		padding-top: 10px;
		box-sizing: border-box;
		padding-bottom: constant(safe-area-inset-bottom);
		/*兼容 iOS<11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容iOS>= 11.2*/
		border-top: 1px solid #e9e9e9;
		padding-left: 15px;
		padding-right: 15px;
	}
</style>